﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using ReferralTracker.Helpers;
using ReferralTracker.BusinessObjects;
using ReferralTracker.Data.Lookups;
using ReferralTracker.Data.Entities;

namespace ReferralTracker.Controllers {
    public class ReferralLinkController : Controller {

        public ActionResult Process(string referralId) {
            var path = string.Format("/{0}", RouteData.Values["path"].ToString());
            var fullpath = Request.Url.GetLeftPart(UriPartial.Authority) + path;
            ActionResult result = HttpNotFound();

            if (WebInfo.IsUrlValid(fullpath)) {
                var account = new AccountManagement();
                var user = account.GetUser(referralId);

                if (user != null) {
                    var registerUrl = WebInfo.GetRegisterReferralUrl(Request, referralId).ToLower();
                    var currentUrl = Request.Url.GetLeftPart(UriPartial.Path).ToLower();

                    if (!currentUrl.Contains(registerUrl)) {
                        var proxy = new ReferralTrackerApiProxy(Request);
                        var referral = new Referral() {
                            User = user,
                            IdReferralType = ReferralType.LinkReferral,
                            ReferralLink = fullpath,
                            ClientIPAddress = WebInfo.GetIpAddress(Request)
                        };
                        var apiResult = proxy.AddReferral(referral);

                        if (apiResult.Headers.Contains("Set-Cookie")) {
                            Response.Headers["Set-Cookie"] = apiResult.Headers.GetValues("Set-Cookie").First();
                        }

                        result = Redirect(path);
                    }
                    else {
                        result = RedirectToRoute(new { controller = "Account", action = "registeruser", referralId = user.UserDetail.ReferralId });
                    }
                }
                account.Dispose();
            }

            return result;
        }

    }
}
